package controllers;

import com.avaje.ebean.Ebean;
import com.fasterxml.jackson.databind.JsonNode;
import models.User;
import play.data.Form;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
import utils.ResponseResult;

import java.util.Date;
import java.util.List;
import java.util.Map;


public class UserController extends Controller {

    public static Result getUsers(){
        List<User> users = User.finder.findList();
        return ok(views.html.userTable.render("",users));
    }

    public static Result getUserInfo(Integer id){
        User user = User.finder.byId(id);
        if(user != null){
            return ok(ResponseResult.ok("",user));
        }
        return ok(ResponseResult.wrong("查询的用户不存在",user));
    }

    public static Result deleteUser(){
        User user = null;
        Map<String,String[]> data = request().body().asFormUrlEncoded();
        if(data.size()>0){
            int id = Integer.parseInt(data.get("id")[0]);
            user = User.finder.byId(id);
            if (user != null){
                Ebean.getServer("default").delete(user);
                List<User> users = User.finder.findList();
                return ok(ResponseResult.ok("用户已经成功删除",users));
            }
        }
        return ok(ResponseResult.wrong("删除的用户不存在",user));
    }

    public static Result saveUser(){
        Form<User> formUser = Form.form(User.class).bindFromRequest();
        if(formUser.hasErrors()) {
            return ok(ResponseResult.wrong("表单填写不符合规则",formUser));
        }else {
            User user = formUser.get();
            if(!checkUserTelExist(user)){
                user.operateTime=new Date();
                Ebean.save(user);
                return  ok(Json.toJson(ResponseResult.ok("新增成功！",user)));
            }
            return ok(Json.toJson(ResponseResult.wrong("手机已经被占用！",user)));
        }
    }
    public static Result updateUser(){
        Form<User> formUser = Form.form(User.class).bindFromRequest();
        if(formUser.hasErrors()) {
            return ok(ResponseResult.wrong("表单填写不符合规则",formUser));
        }else {
            User user = formUser.get();
            User dbUser = User.finder.byId(user.id);
            if (dbUser!=null){
                    Ebean.update(user);
                return ok(Json.toJson(ResponseResult.ok("修改成功！",user)));
            }
            return ok(Json.toJson(ResponseResult.wrong("用户不存在！",user)));
        }
    }
    public static boolean checkUserTelExist(User user){
        String telephone = user.telephone;
        int count = User.finder.where().eq("telephone",telephone).findRowCount();
        if(count>0){
            return true;
        }
        return false;
    }


}
